<?php


namespace app\model;


use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use \Exception as E;

class ShopModel
{
    private static $_table = 'eb_store'; // 商户
    private static $_schoolStoreTable = 'eb_school_store'; //学校-商户关联表
    private static $_schoolTable = 'eb_school'; // 学校
    private static $_adminTable = 'eb_admin'; // 管理员表
    private static $_dorTable = 'eb_dormitory'; // 宿舍表

    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['sl.operate_id', '=', $admin['id']];
            if ($input['is_special'] !== '') $map[] = ['sp.is_special', '=', $input['is_special']];
            if ($input['shop_name'] !== '') $map[] = ['sp.shop_name', 'like', "%{$input['shop_name']}%"];
            if ($input['school_name'] !== '') $map[] = ['sl.school_name', 'like', "%{$input['school_name']}%"];
            $field = 'sp.id,ss.school_id,sl.name as school_name,sp.shop_name,is_special,company_name,address,sort,cert_validity,time_interval,send_range,sp.bank_no,sp.bank_address,sp.bank_phone,sp.bank_name,legal_name,sp.create_time,sp.status,remark,proportion,sp.logo,cert_pic,allow_pic,a.account as admin_account,a.name as admin_name,a.phone as admin_phone,a.status as admin_status,dor_ids';
            $table = Db::table(self::$_table)->alias('sp')
                ->leftJoin([self::$_schoolStoreTable => 'ss'], 'sp.id = ss.store_id')
                ->leftJoin([self::$_schoolTable => 'sl'], 'sl.id = ss.school_id')
                ->leftJoin([self::$_adminTable => 'a'], 'a.id = sp.admin_id')
                ->field($field)
                ->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'data' => []]);
            $data = $table->order('sp.create_time', 'desc')->page($input['page'], $input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'data' => $data]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**类型更改
     * @param $input
     * @param $token
     * @return Json
     */
    public static function changeSpecial($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['id', '=', $input['id']]
            ];
            $update = [
                'is_special' => $input['is_special'],
                'proportion' => $input['is_special'] == 1 ? $input['proportion'] : 0,
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($update);
            if ($rtn) {
                $rtn = Cache::store('redis')->handler()->hMset('dxsd-store-' . $input['id'], $update);
                if ($rtn === true) {
                    Db::commit();
                    return jsonSuccess('更改成功');
                } else {
                    Db::rollback();
                    return jsonFail('无法更改,请刷新页面重新查看');
                }
            } else {
                Db::rollback();
                return jsonFail('无法更改,请刷新页面重新查看');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**商户审核
     * @param $input
     * @param $token
     * @return Json
     */
    public static function edit($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            if ($input['status'] !=2) {//审核通过不用填备注
                $input['remark'] = '';
            }
            $map[] = ['id', '=', $input['id']];
            if ($input['status'] == 1) $map[] = ['sn', '<>', ''];
            $res = Db::table('eb_store')->where($map)->update(['status' => $input['status'], 'remark' => $input['remark']]);
            if ($res) return jsonSuccess('操作成功');
            if ($input['status'] == 1) {
                return jsonFail('未找到商户或者没有绑定打印机');
            } else {
                return jsonFail('操作失败');
            }
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加商户后台账号
     * @param $input
     * @param $token
     * @return Json
     */
    public static function addAdmin($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $storeId = $input['id'];
            $map = [
                ['id', '=', $storeId],
                ['admin_id', '=', 0]
            ];
            unset($input['repwd']);
            unset($input['id']);
            $input['pwd'] = sha1($input['pwd']);
            $input['bank_no'] = '';
            $input['bank_name'] = '';
            $input['type'] = 5;
            $input['pid'] = $admin['id'];
            $input['store_id'] = $storeId;
            $input['create_time'] = time();
            Db::startTrans();
            $flag = true;
            $id = Db::table(self::$_adminTable)->insertGetId($input);
            if ($id > 0) {
                $rtn = Db::table(self::$_table)->where($map)->update(['admin_id' => $id]);
                if ($rtn == 1) {
                    Db::commit();
                    return jsonSuccess('添加成功');
                }
            }
            Db::rollback();
            return jsonFail('添加失败');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            if (stripos($e->getMessage(), "for key 'account'") !== false) return jsonFail('账号已被使用');
            return jsonFail('服务内部错误~');
        }
    }

    /**获取商户后台管理员信息
     * @param $input
     * @param $token
     * @return Json
     */
    public static function storeAdminOnly($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['s.id', '=', $input['id']],
            ];
            $rtn = Db::table(self::$_table)->alias('s')
                ->join([self::$_adminTable => 'a'], 'a.id = s.admin_id')
                ->field('s.id,a.account,a.name,a.phone')
                ->where($map)
                ->find();
            if ($rtn) return jsonSuccess('获取成功', $rtn);
            return  jsonFail('获取失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑商户后台账号
     * @param $input
     * @param $token
     * @return Json
     */
    public static function editAdmin($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $storeId = $input['id'];
            $update = [
                'a.account' => $input['account'],
                'a.name' => $input['name'],
                'a.phone' => $input['phone'],
            ];
            $rtn = Db::table(self::$_table)->alias('sp')
                ->join([self::$_adminTable => 'a'], 'a.id = sp.admin_id')
                ->where('sp.id', $storeId)
                ->update($update);
            if ($rtn) return jsonSuccess('编辑成功');
            return jsonFail('编辑失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑商户后台密码
     * @param $input
     * @param $token
     * @return Json
     */
    public static function editPwdAdmin($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $storeId = $input['id'];
            $update = [
                'a.pwd' => sha1($input['pwd'])
            ];
            $rtn = Db::table(self::$_table)->alias('sp')
                ->join([self::$_adminTable => 'a'], 'a.id = sp.admin_id')
                ->where('sp.id', $storeId)
                ->update($update);
            if ($rtn) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改商户管理员状态
     * @param $input
     * @param $token
     * @return Json
     */
    public static function changeAdminStatus($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
              ['sp.id', '=', $input['id']],
              ['a.status', '=', $input['status'] == 1 ? 0 : 1]
            ];
            $update = [
                'a.status' => $input['status']
            ];
            $rtn = Db::table(self::$_table)->alias('sp')
                ->join([self::$_adminTable => 'a'], 'a.id = sp.admin_id')
                ->where($map)
                ->update($update);
            if ($rtn) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取绑定的楼栋
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getBindDor($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            //商户对应学校的所有楼栋
            $dorList = Db::table(self::$_table)->alias('s')
                ->leftJoin([self::$_schoolStoreTable => 'ss'], 's.id = ss.store_id')
                ->leftJoin([self::$_dorTable => 'd'], 'd.school_id = ss.school_id')
                ->where('ss.store_id', $input['id'])
                ->field('d.id as dor_id, d.name as dor_name,s.dor_ids')
                ->select()->toArray();
            if (!$dorList) return jsonFail('未获取到数据');
            if ($dorList[0]['dor_ids'] == '0') {
                $chooseDorList = [];
            } else {
                $chooseDorList = explode(',', trim($dorList[0]['dor_ids'], ','));
            }
            return jsonSuccess('获取成功', ['dorList' => $dorList, 'chooseDorList' => $chooseDorList]);
        } catch (E $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }
    /**商户绑定楼栋
     * @param $input
     * @param $token
     * @return Json
     */
    public static function bindDor($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            if ($input['chooseDorList']) {
                $input['dor_ids'] = ',' . implode(',', $input['chooseDorList']) . ',';
            } else {
                $input['dor_ids'] = 0;
            }
            $rtn = Db::table(self::$_table)->where('id', $input['id'])->update(['dor_ids' => $input['dor_ids']]);
            if ($rtn) return jsonSuccess('操作成功');
            return jsonFail('操作失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

}